/**
 * statusBar 模块
 * @module statusBar
 * @class statusBar
 */
$(function() {
    var service = window._service
    var config = window._service.config

    var _otaUpdateCancelFlag = null;
    var isLoggedIn = true;
    var fotaResultAlertPopuped = false;
    var trafficAlertPopuped = false;
    var trafficAlert100Popuped = false;
    var resetTrafficAlertPopuped = false;

    /**
     * 初始化ViewModel
     * @method init
     */
    function init() {
        window.setTimeout(function() {
            var vm = new statusViewModel();

            window.setInterval(function() {
                var data = getStatusInfo();
                vm.batteryPers = convertBatteryPers(data.batteryPers, data.batteryStatus);

                var upgradingState = ["prepare_install", "low_battery", "download_success", "downloading"];

                if (data.isLoggedIn == true && !($("#progress").is(":visible")) && data.defaultWanName != "") {
                    if ($.inArray(data.current_upgrade_state, upgradingState) != -1) {
                        if (null == _otaUpdateCancelFlag) {
                            if (!data.is_mandatory) {
                                $.modal.close();
                            }
                            showOtaStatus();
                        } else if (false == _otaUpdateCancelFlag) {
                            _otaUpdateCancelFlag = null;
                        }
                    }
                }

                checkTrafficLimitAlert(data);
            }, 1000);

            var checkOtaResult = function() {
                var info = service.getStatusInfo();
                if (info.isLoggedIn) {
                    service.getUpgradeResult({}, function(data) {
                        if (data.upgrade_result == "success") {
                            showOtaResult(true);
                        } else if (data.upgrade_result == "fail") {
                            showOtaResult(false);
                        } else {
                            window.setTimeout(checkOtaResult, 1000);
                        }
                    }, function() {
                        window.setTimeout(checkOtaResult, 1000);
                    });
                } else {
                    window.setTimeout(checkOtaResult, 1000);
                }
            };
            if (vm.updateType == "mifi_fota") {
                checkOtaResult();
                window.setInterval(function() {
                    var info = getStatusInfo();
                    if (info.isLoggedIn && info.defaultWanName != "") {
                        if (info.new_version_state && info.fota_package_already_download != "yes" && !config.ALREADY_NOTICE) {
                            service.getUpgradeResult({}, function(data) {
                                if (data.upgrade_result == "success") {
                                    showOtaResult(true);
                                } else if (data.upgrade_result == "fail") {
                                    showOtaResult(false);
                                } else {
                                    if (fotaResultAlertPopuped == false) {
                                        config.ALREADY_NOTICE = true;
                                        showOTAAlert();
                                    }
                                }
                            });
                        }
                    }
                }, 1000);
            }
        }, 1200);

        /**
         * 获取当前网络状态
         * 
         * @method getNetworkType
         */
        getNetworkType = function(networkType) {
            var networkTypeTmp = networkType.toLowerCase();
            if (networkTypeTmp == '' || networkTypeTmp == 'limited service') {
                networkTypeTmp = 'limited_service';
            }
            if (networkTypeTmp == 'no service') {
                networkTypeTmp = 'no_service';
            }
            if (networkTypeTmp == 'limited_service' || networkTypeTmp == 'no_service') {
                $("#networkType", "#statusBar").attr("data-trans", "network_type_" + networkTypeTmp);
                return $.i18n.prop("network_type_" + networkTypeTmp);
            } else {
                $("#networkType", "#statusBar").removeAttr("data-trans");
                return networkType;
            }
        };
    }

    /**
     * 获取网络、SIM、WIFI等状态
     * @method getStatusInfo
     */
    var getStatusInfo = function() {
        return service.getStatusInfo();
    };

    /**
     * statusViewModel
     * @class statusViewModel
     */
    function statusViewModel() {
        var self = this;
        var info = getStatusInfo();
        self.isShowFotaNewversionIcon = info.new_version_state && info.fota_package_already_download != "yes" && !config.isShowFotaIcon;
        self.isShowConnectionIcon = false;
        self.isShowRj45ConnectionIcon = false;
        self.hasWifi = config.HAS_WIFI;
        self.hasBattery = config.HAS_BATTERY
        self.updateType = service.getUpdateType().update_type
        self.networkType = info.networkType
        self.roamingStatus = info.roamingStatus ? "R" : ""
        self.pinStatus = info.pinStatus
        self.pinStatusText = '';
        self.batteryStatus = info.batteryStatus
        self.batteryPers = convertBatteryPers(info.batteryPers, info.batteryStatus);
        self.connectStatus = info.connectStatus
        self.connectStatusText = '';
        self.connectStatusTrans = '';
        //self.attachedDevices = ko.observable(info.attachedDevices);
        self.showAttachedDevices = info.wifiStatus
        self.isLoggedIn = info.isLoggedIn
        self.showSmsDeleteConfirm = false
        self.smsUnreadCount = 0
        self.connectionCssClass = ""
        self.rj45ConnectionCssClass = ""
    }

    /**
     * 检查浏览提醒状态
     */
    checkTrafficLimitAlert = function(info) {
        if (window.location.hash == '#login' || window.location.hash == '') {
            return false;
        }

        var APStationEnabled = config.AP_STATION_SUPPORT ? service.getStatusInfo().ap_station_enable : 'undefined';
        //先确定Ap Station使能状态再确定用什么方式来提醒
        if (config.AP_STATION_SUPPORT && (typeof APStationEnabled == "undefined" || APStationEnabled === '')) {
            service.refreshAPStationStatus({}, $.noop());
            return false;
        }

        APStationEnabled = APStationEnabled == 1;
        var inShow = $("#confirm-container:visible").length > 0;
        var notPPP = (config.PRODUCT_TYPE == 'CPE' && checkCableMode(info.blc_wan_mode)) ? true : false;
        if (!info.isLoggedIn || inShow || (trafficAlertPopuped && trafficAlert100Popuped) || !info.limitVolumeEnable || (!APStationEnabled && !(info.connectStatus == "ppp_connected")) || notPPP) {
            return false;
        }

        if (resetTrafficAlertPopuped) {
            window.setTimeout(function() {
                resetTrafficAlertPopuped = false;
            }, 2000);
            return false;
        }

        var trafficResult = getTrafficResult(info);
        if (trafficResult.showConfirm) {
            var confirmMsg = null;
            if (trafficResult.usedPercent > 100 && !trafficAlert100Popuped) {
                trafficAlertPopuped = trafficAlert100Popuped = true;
                confirmMsg = { msg: APStationEnabled ? 'traffic_beyond_msg' : 'traffic_beyond_disconnect_msg' };
            } else if (!trafficAlertPopuped) {
                trafficAlertPopuped = true;
                trafficAlert100Popuped = false;
                confirmMsg = {
                    msg: APStationEnabled ? 'traffic_limit_msg' : 'traffic_limit_disconnect_msg',
                    params: [trafficResult.limitPercent]
                };
            }

            if (confirmMsg != null) {
                if (APStationEnabled) {
                    showAlert(confirmMsg.msg, null, confirmMsg.params);
                } else {
                    showConfirm("", confirmMsg, function() {
                        showLoading("disconnecting");
                        service.disconnect({}, function(data) {
                            if (data.result) {
                                successOverlay();
                            } else {
                                errorOverlay();
                            }
                        });
                    });
                }
            }
        }
        return true;
    };

    /**
     * 将电量转化为对应图片
     * @method convertBatteryPers
     * @param pers
     * @param status
     */
    function convertBatteryPers(pers, status) {
        var src = null;
        if ("0" == status) {
            if ("1" == pers) {
                src = "img/battery_one.png";
            } else if ("2" == pers) {
                src = "img/battery_two.png";
            } else if ("3" == pers) {
                src = "img/battery_three.png";
            } else if ("4" == pers) {
                src = "img/battery_full.png";
            } else { //"5" == pers || "0" == pers
                src = "img/battery_out.png";
            }
        } else {
            src = "img/battery_charging.gif";
        }
        if ($('#batteryCharging') && $('#batteryCharging').attr('src') != src) {
            $('#batteryCharging').attr('src', src)
        }
        return src;
    }

    /**
     * 显示OTA升级结果
     * @method showOtaResult
     */
    function showOtaResult(otaResult) {
        if ((!($("#loading").is(":visible"))) && (!($("#confirm").is(":visible")))) {
            var msg = otaResult ? "ota_update_success" : "ota_update_failed";
            fotaResultAlertPopuped = true;
            showAlert(msg, function() {
                fotaResultAlertPopuped = false;
                if (config.UPGRADE_TYPE == "OTA") {
                    service.clearUpdateResult({}, $.noop());
                }
            });
        } else {
            window.setTimeout(function() {
                showOtaResult(otaResult)
            }, 1000);
        }
    }

    var checkBatteryTimer = 0;

    function CheckBatteryStatus() {
        var state = service.getCurrentUpgradeState();
        if (state.current_upgrade_state == 'low_battery') {
            showInfo('ota_low_battery');
            clearInterval(checkBatteryTimer);
        }
    }

    var timer = 0;
    /**
     * 显示升级状态
     * @method showOtaStatus
     */
    function showOtaStatus() {
        _otaUpdateCancelFlag = true;
        var r = service.getNewVersionState();

        function showProgress() {
            var upgradingState = ["downloading"];
            var info = service.getCurrentUpgradeState();
            if (info.current_upgrade_state.toLowerCase() == "idle") {
                addTimeout(showProgress, 1000);
            } else if (($.inArray(info.current_upgrade_state, upgradingState) != -1) && (r.fota_new_version_state != "already_has_pkg")) {
                hideLoading();
                showOTAUpgradeStatus();
            }
        }
        if (!($("#progress").is(":visible"))) {
            showProgress();
        }
        var times = 0;
        var getOTAUpgradeState = function() {
            var data = null;
            if (times <= 3) {
                times = times + 1;
                data = service.getCurrentUpgradeState();
            } else {
                data = getStatusInfo();
            }
            var state = data.current_upgrade_state;
            if (_otaUpdateCancelFlag && isLoggedIn == true) {

                if (r.fota_new_version_state == "already_has_pkg") {
                    if (state == 'low_battery') {
                        hideProgressBar();
                        _otaUpdateCancelFlag = false;
                        service.removeTimerThings('fota_current_upgrade_state', function() {});
                        showInfo('ota_pkg_low_battery');
                        window.clearTimeout(timer);

                        return;
                    } else if (state == 'prepare_install') {
                        hideProgressBar();
                        _otaUpdateCancelFlag = false;
                        service.removeTimerThings('fota_current_upgrade_state', function() {});
                        showInfo('ota_pkg_download_success', null, null, 180);
                        window.clearTimeout(timer);
                        checkBatteryTimer = setInterval(function() {
                            CheckBatteryStatus();
                        }, 1000);
                        return;
                    }
                } else if (state == 'downloading') {
                    getDownloadSize();
                } else if (state == 'download_failed') {
                    hideProgressBar();
                    _otaUpdateCancelFlag = false;
                    showAlert('ota_download_failed');
                    window.clearTimeout(timer);
                    return;
                } else if (state == 'low_battery') {
                    hideProgressBar();
                    _otaUpdateCancelFlag = false;
                    service.removeTimerThings('fota_current_upgrade_state', function() {});
                    showInfo('ota_low_battery');
                    window.clearTimeout(timer);
                    return;
                } else if (state == 'prepare_install') {
                    hideProgressBar();
                    _otaUpdateCancelFlag = false;
                    service.removeTimerThings('fota_current_upgrade_state', function() {});
                    showInfo('ota_download_success', null, null, 180);
                    window.clearTimeout(timer);
                    checkBatteryTimer = setInterval(function() {
                        CheckBatteryStatus();
                    }, 1000);
                    return;
                } else {
                    _otaUpdateCancelFlag = false;
                    hideProgressBar();
                    window.clearTimeout(timer);
                    return;
                }
                timer = window.setTimeout(getOTAUpgradeState, 1000);
            }
        };

        if (_otaUpdateCancelFlag && isLoggedIn == true) {
            timer = window.setTimeout(getOTAUpgradeState, 100);
        } else {
            window.clearTimeout(timer);
        }
    }

    function getUserSelector(choice) {
        var info = getStatusInfo();
        if (choice) {
            var modeData = service.getOpMode();
            if (!checkConnectedStatus(info.connectStatus, modeData.rj45_state, info.connectWifiStatus)) {
                showAlert("ota_network_disconnected");
                return;
            }

            if (info.fota_user_selector == 'none') {
                startOTAUpgrade();
            } else if (info.fota_user_selector == 'accept') {
                showOtaStatus();
            } else if (info.fota_user_selector == 'cancel') {
                showAlert("ota_have_cancel");
            } else if (info.fota_user_selector == 'downloading_cancel') {
                showAlert("ota_have_cancel");
            }
        } else {
            if (info.fota_user_selector == 'none') {
                cancelOTAUpgrade();
            } else if (info.fota_user_selector == 'accept') {
                showOtaStatus();
            } else if (info.fota_user_selector == 'cancel') {

            } else if (info.fota_user_selector == 'downloading_cancel') {

            }
        }
    }
    /**
     * 获取升级包大小
     * @method getDownloadSize
     */
    function getDownloadSize() {
        service.getPackSizeInfo({}, function(data) {
            var percents;
            if (parseInt(data.fota_pkg_total_size) == 0) {
                percents = 0;
            } else {
                percents = parseInt(parseInt(data.fota_dl_pkg_size) * 100 / parseInt(data.fota_pkg_total_size));
            }
            if (percents > 100) {
                percents = 100;
            }
            if (percents >= 0) {
                if (percents > 95) {
                    showProgressBar("ota_update", "<br/>" + $.i18n.prop("ota_update_warning"));
                }
                setProgressBar(percents);
            }
        });
    }

    function startOTAUpgrade() {
        service.setUpgradeSelectOp({ selectOp: '1' }, function(result) {
            if (result.result == "success") {
                showOtaStatus();
            }
        });
    }

    function cancelOTAUpgrade() {
        service.setUpgradeSelectOp({ selectOp: '0' }, function(result) {});
    }
    /**
     * 显示当前升级状态
     * @method showOTAUpgradeStatus
     */
    function showOTAUpgradeStatus() {
        var data = service.getMandatory();
        var isMandatory = data.is_mandatory;
        var sizeInfo = service.getPackSizeInfo();
        var percents;

        if (parseInt(sizeInfo.fota_pkg_total_size) == 0) {
            percents = 0;
        } else {
            percents = parseInt(parseInt(sizeInfo.fota_dl_pkg_size) * 100 / parseInt(sizeInfo.fota_pkg_total_size));
        }
        if (percents > 100) {
            percents = 100;
        }

        if (isMandatory) {
            showProgressBar("ota_update", "<br/>" + $.i18n.prop("ota_update_warning"));
        } else {
            var cancelHtml = "";
            if (config.UPGRADE_TYPE == "OTA") {
                cancelHtml = "<br/><br/><button id='btnStopUpgrade' onclick='stopOTAUpgrade();' class='btn-1 btn-primary'>" + $.i18n.prop("cancel") + "</button>";
            }
            showProgressBar("ota_update", "<br/>" + $.i18n.prop("ota_update_warning") + cancelHtml);
        }

        //setProgressBar(0);
        if (percents >= 0) {
            setProgressBar(percents);
        }
    }
    /**
     * 显示有新版本或升级中断提示
     * @method showOTAConfirm
     */
    function showOTAConfirm(upgradeState) {
        var upgState = upgradeState.current_upgrade_state;
        if (upgState == 'upgrade_pack_redownload') {
            showConfirm('', "ota_interrupted", function() { getUserSelector(1); }, function() { getUserSelector(0); });
        } else {
            var upgradingState = ["prepare_install", "low_battery",
                "connecting_server", "connect_server_success", "downloading", "accept"
            ];
            if ($.inArray(upgState, upgradingState) != -1) {
                showOtaStatus();
            } else {
                showConfirm('', "ota_new_version", function() {
                    getUserSelector(1);
                    config.ISNOW_NOTICE = false;
                }, function() {
                    getUserSelector(0);
                    config.ISNOW_NOTICE = false;
                });
            }
        }
    }

    showOTAAlert = function() {
        config.ISNOW_NOTICE = true;
        var is_mandatory = service.getMandatory().is_mandatory;
        if (is_mandatory) {
            showOtaStatus();
        } else {
            var upgradeState = {};
            upgradeState = service.getCurrentUpgradeState();
            showOTAConfirm(upgradeState);
        }
    };

    /**
     * 终止OTA升级
     * @method stopOTAUpgrade
     */
    stopOTAUpgrade = function() {
        service.setUpgradeSelectOp({ selectOp: '2' }, function(result) {});
        _otaUpdateCancelFlag = false;
        window.clearTimeout(timer);
        hideLoading();
        showAlert('ota_cancel');
    };

    /**
     * sim状态图标
     */
    getSimStatusImg = function(status) {
        var t;
        switch (status) {
            case "modem_init_complete":
                t = "img/sim_detected.png";
                break;
            case "modem_waitpin":
            case "modem_waitpuk":
            case "modem_sim_undetected":
            case "modem_undetected":
            case "modem_imsi_waitnck":
            case "modem_sim_destroy":
            case "modem_destroy":
                t = "img/sim_undetected.png";
                break;
            default:
                t = "img/sim_detected.png"
        }
        return t
    }

    /**
     * 网络链接状态图标
     */
    getConnectionStatusImg = function(statusInfo, hotspotList) {
        var t = statusInfo.connectStatus;
        var n = statusInfo.data_counter;
        var s = statusInfo.connectWifiSSID;
        var i = statusInfo.connectWifiStatus;
        var a = "icon_connection ";
        if ("ppp_disconnected" == t) {
            if (s && "connect" == i) {
                for (var nn = "icon_connection ", o = "connecting ", ss = 0, ii = hotspotList.length; ss < ii; ss++)
                    if ("1" == hotspotList[ss].connectStatus) {
                        o = "wifi_connected";
                        break
                    }
                nn += o;
                return nn;
            }
            a += s && "connecting" == i ? "connecting" : "disconnect"
        } else "ppp_connecting" == t || "wifi_connecting" == t ? a += "connecting" : "0" != n.uploadRate && "0" != n.downloadRate ? a += "connectionBoth" : "0" != n.uploadRate && "0" == n.downloadRate ? a += "connectionUp" : "0" == n.uploadRate && "0" != n.downloadRate ? a += "connectionDown" : a += "connectionNone";

        return a;
    }

    /**
     * wifi状态图标
     */
    getWifiStatusImg = function(wifiStatus) {
        return wifiStatus ? "./img/wifi_1.png" : "./img/wifi_0.png"
    }

    /**
     * 电池充电图标
     */
    getBatteryPersImg = function(battery_value, batteryStatus) {
        var n = parseInt(battery_value);
        return "0" == batteryStatus ?
            n >= 0 && n <= 5 ?
            "img/battery_out.png" : n > 5 && n <= 25 ?
            "img/battery_one.png" : n > 25 && n <= 50 ?
            "img/battery_two.png" : n > 50 && n <= 90 ?
            "img/battery_three.png" : "img/battery_full.png" : "2" == batteryStatus ?
            "img/battery_full.png" : n >= 0 && n <= 5 ?
            "img/battery_charging.gif" : n > 5 && n <= 25 ?
            "img/battery_charging1.gif" : n > 25 && n <= 50 ?
            "img/battery_charging2.gif" : n > 50 && n <= 90 ?
            "img/battery_charging3.gif" : "img/battery_full.png"
    }

    getSignalIcon = function(statusInfo) {
        var i = statusInfo;
        var e = i.networkType.toLowerCase(),
            n = i.simStatus ? i.simStatus.toLowerCase() : "";
        // "" != e && "limited service" != e && "no service" != e && "modem_init_complete" == n || i.signalImg(0);
        if (e == '' || e == 'limited service' || e == 'limited_service' || e == 'no service' || e == 'no_service') {
            i.signalImg = 0;
        }
        return 0 == i.signalImg ?
            "img/icon_signal_00.png" : 1 == i.signalImg ?
            "img/icon_signal_01.png" : 2 == i.signalImg ?
            "img/icon_signal_02.png" : 3 == i.signalImg ?
            "img/icon_signal_03.png" : 4 == i.signalImg ?
            "img/icon_signal_04.png" : 5 == i.signalImg ?
            "img/icon_signal_05.png" : "img/icon_signal_00.png"
    }

    getConnectStatusText = function(statusInfo) {
        return canConnect(statusInfo), checkConnectedStatus(statusInfo.connectStatus) ? $.i18n.prop("connected") : $.i18n.prop("disconnected")
    }

    canConnect = function(statusInfo) {
        if ("modem_init_complete" != statusInfo.simStatus) return !1;
        if (checkConnectedStatus(statusInfo.connectStatus)) {
            if (window._service.config.AP_STATION_SUPPORT && 1 == statusInfo.ap_station_enable) {
                if ("auto_dial" == window._service.getConnectionMode().connectionMode)
                    return !1
            }
            return !0
        }
        if ("0" == statusInfo.signalImg) return !1;

        var n = statusInfo.networkType.toLowerCase();
        return "" != n && "limited_service" != n && "no_service" != n && ("ppp_connecting" != statusInfo.connectStatus && "ppp_disconnecting" != statusInfo.connectStatus && (!window._service.config.AP_STATION_SUPPORT || "connect" != statusInfo.connectWifiStatus || "wifi_pref" != statusInfo.ap_station_mode))
    }

    getMobileConnectBtnClass = function(connectStatus) {
        return checkConnectedStatus(connectStatus) ? "mobile_connect_btn_on" : "mobile_connect_btn"
    }

    /**
     * 设置流量提醒是否提醒过
     */
    setTrafficAlertPopuped = function(val) {
        trafficAlertPopuped = !!val;
        trafficAlert100Popuped = !!val;
        if (!val) {
            resetTrafficAlertPopuped = true;
        }
    }

    setTrafficAlert100Popuped = function(val) {
        trafficAlert100Popuped = !!val;
        if (!val) {
            resetTrafficAlertPopuped = true;
        }
    }

    /**
     * 计算流量结构
     */
    getTrafficResult = function(info) {
        var trafficResult = {
            showConfirm: false,
            limitPercent: info.limitVolumePercent
        };
        if (info.limitVolumeType == '1') {
            var monthlyTraffic = parseInt(info.data_counter.monthlySent, 10) + parseInt(info.data_counter.monthlyReceived, 10);
            trafficResult.usedPercent = monthlyTraffic / info.limitVolumeSize * 100;
            if (trafficResult.usedPercent > trafficResult.limitPercent) {
                trafficResult.showConfirm = true;
                trafficResult.type = 'data';
            }
        } else {
            trafficResult.usedPercent = info.data_counter.monthlyConnectedTime / info.limitVolumeSize * 100;
            if (trafficResult.usedPercent > trafficResult.limitPercent) {
                trafficResult.showConfirm = true;
                trafficResult.type = 'time';
            }
        }
        return trafficResult;
    }

    window._status = {
        init: init,
        showOTAAlert: showOTAAlert,
        getSimStatusImg: getSimStatusImg,
        getConnectionStatusImg: getConnectionStatusImg,
        getWifiStatusImg: getWifiStatusImg,
        getBatteryPersImg: getBatteryPersImg,
        getSignalIcon: getSignalIcon,
        getConnectStatusText: getConnectStatusText,
        canConnect: canConnect,
        getMobileConnectBtnClass: getMobileConnectBtnClass,
        setTrafficAlertPopuped: setTrafficAlertPopuped,
        getTrafficResult: getTrafficResult,
        setTrafficAlert100Popuped: setTrafficAlert100Popuped
    };
});